<?php

namespace App\Admin\Actions\Keyword;

use App\Miya\Models\Area;
use App\Miya\Models\Keyword;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Derivative extends Action
{
    protected $selector = '.derivative';

    public function handle(Request $request)
    {
        $areas = Area::all();
        Keyword::with(['area'])->get()->each(function ($keyword) use ($areas) {
            $insertData = app('admin_keyword')->buildDerivative($keyword, $areas);
            $insertDataArray = array_chunk($insertData, 100);
            foreach ($insertDataArray as $data) {
                DB::table('derivative_keywords')->insertOrIgnore($data);
            }
        });

        return $this->response()->success('衍生词生成完成')->refresh();
    }

    public function dialog()
    {
        $areacount = area::count();
        $keywordcount = keyword::count();
        if ($areacount > 15 || $keywordcount > config('keyword.max_count')) {
            $this->confirm('生成衍生词数量可能过多,建议点击"取消"并逐个生成衍生词!');
        } else {
            $this->confirm('确定批量生成衍生词吗?');
        }
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-success derivative">生成衍生词</a>
HTML;
    }
}
